# D:\dazuoye\app\views\sales_channel.py

from flask import Blueprint, jsonify
from app.data_loader import sales_performance_data
import pandas as pd

sales_bp = Blueprint('sales_channel', __name__)

@sales_bp.route('/api/sales/channel_performance', methods=['GET'])
def get_channel_performance():
    """API: 渠道销售额对比柱状图"""
    if sales_performance_data is None: return jsonify({"error": "销售业绩数据未能加载"}), 500
    performance = sales_performance_data.groupby('渠道')['总交易额(GMV)'].sum().sort_values(ascending=False)
    return jsonify({"channels": performance.index.tolist(), "gmv": performance.values.tolist()})

@sales_bp.route('/api/sales/conversion_funnel', methods=['GET'])
def get_conversion_funnel():
    """API: 转化率漏斗图"""
    if sales_performance_data is None: return jsonify({"error": "销售业绩数据未能加载"}), 500
    conversion_rate = sales_performance_data.groupby('渠道')['转化率%'].mean().sort_values(ascending=False)
    return jsonify([{"value": round(rate, 2), "name": channel} for channel, rate in conversion_rate.items()])